<?php
require_once dirname(__FILE__) . "/../OaSyncInfoLogic.php";
require_once OPEN_LIB_PATH . '/open/interfaces/InterfaceFactory.php';
class OaServiceSync
{
	private $_appModel;
	
	private $_logger;
    
	public function __construct()
	{
		$this->_appModel = new OaAppModel();
		$this->_logger = OaLogic::getLogger();
    }
     /**
     * 同步区组信息到计费网关
     * @param $appId
     * @param $areaId 区编号
     * @param $areaName
     * @param $env
     * @param $op
     * 
     * @return boolean
     */
    public function _syncBillingArea ($appId, $areaId, $areaName, $env, $op = 'add')
    {
        $this->_logger->info("_syncBillingArea, app-$appId, areaId-{$areaId},env-$env");
    	$this->_appModel->setCurrentConfigEnv($env);
        $appRow = $this->_appModel->getAppConfig($appId, array('service_billing_status'));
        if (!$appRow || $appRow['service_billing_status'] != OaAppModel::APP_SERVICE_STATUS_OPENED) {
            return true;
        }
        InterfaceFactory::load("BillingInterface");
        $billInc = InterfaceFactory::getInc("BillingInterface");
        $env = $env == OaAppModel::APP_CONFIG_ENV_TEST ? BillingInterface::APP_ENV_TEST : BillingInterface::APP_ENV_PRODUCTION;
        $method = '';
        switch ($op) {
            case 'add':
                $method = BillingInterface::BILLING_AREA_OP_ADD;
                break;
            case 'update':
                $method = BillingInterface::BILLING_AREA_OP_UPDATE;
                break;
            case 'delete':
                $method = BillingInterface::BILLING_AREA_OP_DELETE;
                break;
            default:
        }
        if (! $method) {
            $this->_logger->log("sync billing failure: undefined {$method}");
            return false;
        }
        $args = array('appId'=>$appId, 'areas'=>array(
            array('areaId'=>$areaId, 'areaName'=>$areaName, 'op'=>$method
            )
        ));
        if (! $billInc->sync($args, $env)) {
            $errNo = $billInc->getErrNo();
            $errMsg = $billInc->getErrMsg();
            $this->_logger->log("sync billing failure: errNo-{$errNo}, errMsg-{$errMsg}");
            return false;
        }
        return true;
    } 
	/**
     * 批量同步信任IP
     * @param int $appId
     * @return boolean
     */
    public function syncTrustIp($appId)
    {
        $this->_logger->info("syncTrustIp, app-$appId");
    	InterfaceFactory::load("AuthenInterface");
        $authInc = InterfaceFactory::getInc("AuthenInterface");
        $args = array('appId'=>$appId, 'trustIp'=>array());
        $appServerModel = new OaAppServerModel(OaAppModel::APP_CONFIG_ENV_PRODUCTION);
        $loginServers = $appServerModel->getAppLoginServers($appId);
        foreach ($loginServers as $loginServer) {
        	$rows = $appServerModel->getLoginServerValidTo($loginServer['id']);
            foreach($rows as $row){
                $areaCode = $row['valid_to_area']==-1 ? $row['valid_to_area']:$row['area_code'];
                $groupCode = $row['valid_to_group']==-1 ? $row['valid_to_group']:$row['area_code'];
                $args['trustIp'][] = array('ip'=>$row['ip'], 'areaId'=>$areaCode,'groupId'=>$groupCode, 'op'=>AuthenInterface::TRUST_IP_ADD);
        	}
        }
        if (!empty($args['trustIp'])) {
        	if (!$authInc->sync($args, AuthenInterface::APP_ENV_PRODUCTION)) {
        	    $errNo = $authInc->getErrNo();
                $errMsg = $authInc->getErrMsg();
                $this->_logger->log("add Trust Ip login valid failed: errNo-{$errNo}, errMsg-{$errMsg}, app-{$appId}");
        		return false;
        	}
        }
        return true;
    }
    /**
     * 添加信任IP
     * @param int $appId 应用ID
     * @param int $areaCode
     * @param int $groupCode
     * @param string $ip 
     * @param $environment 环境变量
     * @param $enforce 是否强添加
     * @return boolean
     */
    public function addTrustIp($appId, $areaCode, $groupCode, $ip, $environment, $enforce=false)
    {
        $this->_logger->info("addTrustIp, app-$appId, areaCode-{$areaCode}, groupCode-{$groupCode}, 
        ip-{$ip}, env-{$environment}, enforce-".intval($enforce));
    	if (!$enforce) {
            if ($environment == OaAppModel::APP_CONFIG_ENV_PRODUCTION) {
            	$appRow = $this->_appModel->getApp($appId, array('need_trust_ip'));
            	if (isset($appRow['need_trust_ip']) && $appRow['need_trust_ip']==OaAppModel::APP_NEED_TRUST_IP) {
            	    $enforce = true;
            	}
            }
        }
        if (!$enforce) {
        	return true;
        }
        InterfaceFactory::load("AuthenInterface");
        $authInc = InterfaceFactory::getInc("AuthenInterface");
        $args = array('appId'=>$appId, 'trustIp'=>array(
            array('ip'=>$ip, 'areaId'=>$areaCode,'groupId'=>$groupCode, 'op'=>AuthenInterface::TRUST_IP_ADD)
        ));
        if (!$authInc->sync($args, AuthenInterface::APP_ENV_PRODUCTION)) {
    	    $errNo = $authInc->getErrNo();
            $errMsg = $authInc->getErrMsg();
            $this->_logger->log("add Trust Ip login valid failed: errNo-{$errNo}, errMsg-{$errMsg}, ip-$ip,app-{$appId}");
    		return false;
    	}
        return true;
    }

    /**
     * 同步区组信息到计费网关（批量）
     * @param $appId
     * @param $env
     * @param $enforce 是否强制开通
     * @param $op
     * 
     * @return boolean
     */
    public function syncBillingArea ($appId, $env, $enforce=false, $op="add")
    {
        $this->_logger->info("syncBillingArea, app-$appId, op-$op, env-$env");
        $this->_appModel->setCurrentConfigEnv($env);
        if (!$enforce) {            
            $appRow = $this->_appModel->getAppConfig($appId, array('service_billing_status'));
            if (!$appRow || $appRow['service_billing_status'] != OaAppModel::APP_SERVICE_STATUS_OPENED) {
                return true;
            }
        }
        $appServerModel = new OaAppServerModel($env);
        $areas = $appServerModel->getAppAreas($appId);
        if ($areas) {
            InterfaceFactory::load("BillingInterface");
            $billInc = InterfaceFactory::getInc("BillingInterface");
            $method = '';
            switch ($op) {
                case 'add':
                    $method = BillingInterface::BILLING_AREA_OP_ADD;
                    break;
                case 'update':
                    $method = BillingInterface::BILLING_AREA_OP_UPDATE;
                    break;
                case 'delete':
                    $method = BillingInterface::BILLING_AREA_OP_DELETE;
                    break;
                default:
            }
        	
            $env = $env == OaAppModel::APP_CONFIG_ENV_TEST ? BillingInterface::APP_ENV_TEST : BillingInterface::APP_ENV_PRODUCTION;
            $args = array('appId'=>$appId, 'areas'=>array());
        	foreach($areas as $area) {
        	    $args['areas'][] = array(
            		'areaId'=>$area['area_code'], 'areaName'=>$area['name'], 'op'=>$method
                );
        	}
        	unset($areas);
            if (! $billInc->sync($args, $env)) {
                $errNo = $billInc->getErrNo();
                $errMsg = $billInc->getErrMsg();
                $this->_logger->log("sync billing failure: errNo-{$errNo}, errMsg-{$errMsg}");
                return false;
            }
        }
        return true;
    } 
    
    private function _syncQftcFgBatch($appId, $env)
    {
        $this->_logger->info("_syncQftcFgBatch, app-$appId, env-$env");
        $appServerModel = new OaAppServerModel($env);
        $payServers = $appServerModel->getAppPayServers($appId);
        foreach ($payServers as $payServer) {
	        $rows = $appServerModel->getPayServerValidTo($payServer['id']);
        	foreach($rows as $row){
        	    if ($row['qft_id'] && !OaSyncInfoLogic::syncPayServerValidToInfo($row['id'], 'update')){
        	    	$this->_logger->log("sync oa qftcfg failure: pay_server_valid_to_{$row['id']}");
        	    	return false;
        	    }
        	}
        }
        return true;
    }
	/**
     * 同步区组信息到支付
     * @param $companyId
     * @param $appId
     * @param $env
     * @param $enforce 是否强制开通
     * 
     * @return boolean
     */
    public function syncPaymentArea ($companyId, $appId, $env, $enforce=false)
    {
        $this->_logger->info("syncPaymentArea, company-$companyId, app-$appId, env-$env, enforce-".intval($enforce));
        $this->_appModel->setCurrentConfigEnv($env);
        if (!$enforce) {        	
            $appRow = $this->_appModel->getAppConfig($appId, array('service_pay_status'));
            if (!$appRow || $appRow['service_pay_status'] != OaAppModel::APP_SERVICE_STATUS_OPENED) {
                return true;
            }
        }
        InterfaceFactory::load("PaymentInterface");
        $payInc = InterfaceFactory::getInc("PaymentInterface");
        $tmpEnv = $env;
        $env = $env == OaAppModel::APP_CONFIG_ENV_TEST ? PaymentInterface::APP_ENV_TEST : PaymentInterface::APP_ENV_PRODUCTION;
        $args = array('spId'=>$companyId, 'appId'=>$appId, 'syncArea'=>1);
        $this->_logger->info("syncPaymentArea, company-$companyId, app-$appId, env-$env, params-".print_r($args, true));
        if (! $payInc->sync($args, $env)) {
            $errNo = $payInc->getErrNo();
            $errMsg = $payInc->getErrMsg();
            $this->_logger->log("sync payment area failure: errNo-{$errNo}, errMsg-{$errMsg}");
            return false;
        }
        $this->_syncQftcFgBatch($appId, $tmpEnv);
        return true;
    }
    
    /**
     * 更新测试账号内测属性
     * @param int $appId
     * @param int $areaId 区编号
     * @param int $perMisson
     * @param int $env
     * 
     * @return void
     */
    public function updateTestPermissionByArea ($appId, $areaId, $perMisson = 1, $env)
    {
        $this->_logger->info("updateTestPermissionByArea, app-$appId, area-{$areaId}, env-$env, per-{$perMisson}");
    	$appRow = $this->_appModel->getApp($appId, array('status'));
        $this->_logger->info("updateTestPermissionByArea, appId-{$appId} ");
        if (!$appRow || $appRow['status'] == OaAppModel::APP_STATUS_IN_OPERATION) {
            return true;
        }
        $otherEnv = OaAppModel::APP_CONFIG_ENV_TEST;
        if ($env == $otherEnv) {
            $otherEnv = OaAppModel::APP_CONFIG_ENV_PRODUCTION;
        }
        $appServerModel = new OaAppServerModel();
        if ($appServerModel->getAreaByAreaCode($appId, $areaId, $otherEnv)) {
            return true;
        }
        $rows = $this->_appModel->getAppTestAccounts($appId, 0, null, OaAppModel::APP_CONFIG_ENV_PRODUCTION, 0);
        if ($rows) {
            InterfaceFactory::load("AuthenInterface");
            $authInc = InterfaceFactory::getInc("AuthenInterface");
            $args = array('appId'=>$appId, 'testAccounts'=>array());
            foreach ($rows as $row) {
                if (is_numeric($row['pt'])) {
                    $row['pt'] .= OaAppModel::PT_SUFFIX;
                } elseif (strstr($row['pt'], "@")) {
                    $ptResult = User::convertId($row['pt']);
                    if ($ptResult[0] != 0) {
                        $this->_logger->info("updateTestPermissionByArea, convert id failed: {$ptResult[1]}");
                    } else {
                	    $row['pt'] = $ptResult[1];
                    }
                	unset($ptResult);
                }
                $args['testAccounts'][] = array('op'=>AuthenInterface::TEST_ACCOUNTS_ADD, 'account'=>$row['pt'], 'areaId'=>$areaId);
            }
            unset($rows);        
            if (!$authInc->sync($args, AuthenInterface::APP_ENV_PRODUCTION)) {
        	    $errNo = $authInc->getErrNo();
                $errMsg = $authInc->getErrMsg();
                $this->_logger->log("sync authen permission fail: errNo-{$errNo}, errMsg-{$errMsg}, app-{$appId}");
        		return false;
        	}
        }
        return true;
    }
    /**
     * 更新测试账号支付授权
     * @param int $spId
     * @param int $appId
     * @param int $env
     * 
     * @return boolean
     */
    public function updatePayPermission ($spId, $appId, $env = null)
    {
        if (!$env) {
        	$env = OaAppModel::APP_CONFIG_ENV_TEST;
        }
        $this->_logger->info("updatePayPermission, company-{$spId}, app-$appId, env-".intval($env));
        $rows = $this->_appModel->getAppTestAccounts($appId, 0, null, OaAppModel::APP_CONFIG_ENV_PRODUCTION, 0);
        $args = array('spId'=>$spId, 'appId'=>$appId, 'testAccounts'=>array());
        if ($rows) {
            foreach ($rows as $row) {
                if (is_numeric($row['pt'])) {
                    $row['pt'] .= OaAppModel::PT_SUFFIX;
                } elseif (strstr($row['pt'], "@")) {
                    $ptResult = User::convertId($row['pt']);
                    if ($ptResult[0] == 0) {
                        $row['pt'] = $ptResult[1];
                    }                	
                	unset($ptResult);
                }
                $args['testAccounts'][] = $row['pt'];
            }
            unset($rows);
        }
        if (! $args['testAccounts']) {
            $args['testAccounts'][] = - 1;
        }
        InterfaceFactory::load("PaymentInterface");
        $payInc = InterfaceFactory::getInc("PaymentInterface");
        $env = $env == OaAppModel::APP_CONFIG_ENV_TEST ? PaymentInterface::APP_ENV_TEST : PaymentInterface::APP_ENV_PRODUCTION;
        if (! $payInc->sync($args, $env)) {
            $errNo = $payInc->getErrNo();
            $errMsg = $payInc->getErrMsg();
            $this->_logger->log("sync payservice testAccounts fail: errNo-{$errNo}, errMsg-{$errMsg}, app-{$appId}");
            return false;
        }
        return true;
    } 
}
